package com.sdhs.workflow.utils;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sdhs.workflow.common.constant.AuthConstants.SignType;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.Serializable;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Map;
import java.util.Random;
import java.util.Set;

public class SignUtil implements Serializable {

    private static final long serialVersionUID = 132889397947066539L;

    private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    private static final Random RANDOM = new SecureRandom();

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。使用MD5签名。
     *
     * @param data     String类型数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @return 签名是否正确
     * @throws Exception 数据缺失异常
     */
    public static boolean isSignatureValid(Map<String, String> data, String sign, String key, String nonceStr) throws Exception {
        return isSignatureValid(data, sign, key, nonceStr, SignType.MD5);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception 数据缺失异常
     */
    public static boolean isSignatureValid(Map<String, String> data, String sign, String key, String nonceStr, SignType signType) throws Exception {
        if (data == null || data.isEmpty()) {
            return false;
        }
        if (StringUtils.isBlank(sign)) {
            return false;
        }
        String signCheck = generateSignature(data, key, nonceStr, signType);
        return signCheck.equals(sign);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data Map类型数据
     * @param key  API密钥
     * @return 签名是否正确
     * @throws Exception 数据缺失异常
     */
    public static boolean isSignatureValid(JSONObject data, String sign, String key, String nonceStr) throws Exception {
        return isSignatureValid(data, sign, key, nonceStr, SignType.MD5);
    }

    /**
     * 判断签名是否正确，必须包含sign字段，否则返回false。
     *
     * @param data     Map类型数据
     * @param key      API密钥
     * @param signType 签名方式
     * @return 签名是否正确
     * @throws Exception 数据缺失异常
     */
    public static boolean isSignatureValid(JSONObject data, String sign, String key, String nonceStr, SignType signType) throws Exception {
        if (data == null || data.isEmpty()) {
            return false;
        }
        if (StringUtils.isBlank(sign)) {
            return false;
        }
        String signCheck = generateSignature(data, key, nonceStr, signType);
        return signCheck.equals(sign);
    }

    /**
     * 生成签名
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @return 签名
     * @throws Exception 数据缺失异常
     */
    public static String generateSignature(final Map<String, String> data, String key, String nonceStr) throws Exception {
        return generateSignature(data, key, nonceStr, SignType.MD5);
    }

    /**
     * 生成签名
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @return 签名
     * @throws Exception 数据缺失异常
     */
    public static String generateSignature(final Map<String, String> data, String key, String nonceStr, SignType signType) throws Exception {
        if (data == null || data.size() == 0) {
            throw new Exception("待数据信息为空");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(data);
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        return generateSignature(jsonObject, key, nonceStr, signType);
    }

    /**
     * 生成签名
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @return 签名
     * @throws Exception 数据缺失异常
     */
    public static String generateSignature(final JSONObject data, String key, String nonceStr) throws Exception {
        return generateSignature(data, key, nonceStr, SignType.MD5);
    }

    /**
     * 生成签名
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @return 签名
     * @throws Exception 数据缺失异常
     */
    public static String generateSignature(final JSONObject data, String key, String nonceStr, SignType signType) throws Exception {
        if (data == null || data.size() == 0) {
            throw new Exception("待数据信息为空");
        }
        Set<String> keysSet = data.keySet();
        Object[] keys = keysSet.toArray();
        Arrays.sort(keys);
        StringBuilder temp = new StringBuilder();
        for (Object k : keys) {
            temp.append(k).append("=");
            String value = data.getString(String.valueOf(k));
            if (StringUtils.isNotBlank(value)) {
                temp.append(value);
            }
            temp.append("&");
        }
        return generateSignature(temp.toString(), key, nonceStr, signType);
    }

    /**
     * 生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
     *
     * @param data     待签名数据
     * @param key      API密钥
     * @param nonceStr 随机字符串
     * @param signType 签名方式
     * @return 签名
     * @throws Exception 数据缺失异常
     */
    private static String generateSignature(final String data, String key, String nonceStr, SignType signType) throws Exception {
        if (StringUtils.isBlank(data)) {
            throw new Exception("待数据信息为空");
        }
        if (StringUtils.isBlank(signType.toString())) {
            throw new Exception("签名方式为空");
        }
        if (key.trim().length() != 32) {
            throw new Exception("API密钥长度不是32位");
        }
        if (nonceStr.trim().length() != 32) {
            throw new Exception("字符串长度不是32位");
        }
        String signString = "key=" + key + "&" + "data=" + data + "&" + "nonceStr=" + nonceStr;
        signString = signString.replaceAll("\"", "").replaceAll(" ", "");
        if (SignType.MD5.equals(signType)) {
            return MD5(signString);
        } else if (SignType.HMACSHA256.equals(signType)) {
            return HMACSHA256(signString, key);
        } else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] dataBytes = md.digest(data.getBytes(StandardCharsets.UTF_8));
        md.update(dataBytes);
        byte[] digest = md.digest();
        StringBuilder hexString = new StringBuilder();
        // 字节数组转换为 十六进制数
        for (byte b : digest) {
            String shaHex = Integer.toHexString(b & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        return hexString.toString().toUpperCase();
    }

    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100), 1, 3);
        }
        return sb.toString().toUpperCase();
    }

    /**
     * 获取随机字符串 NonceStr
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }

    /**
     * 获取当前时间戳，单位秒
     *
     * @return 时间戳-秒
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获取当前时间戳，单位毫秒
     *
     * @return 时间戳-毫秒
     */
    public static long getCurrentTimestampMs() {
        return System.currentTimeMillis();
    }
}
